package cn.stylefeng.guns.sys.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.sys.core.auth.cache.SessionManager;
import cn.stylefeng.roses.core.util.ToolUtil;

@Component
public class WxTool {
	
	@Autowired
    private SessionManager sessionManagerSelf;
	
	private static SessionManager sessionManager;
	
	private static String ACCESS_TOKEN_KEY = "accessToken";

	private static String loginUrl = "https://api.weixin.qq.com/sns/jscode2session";//登录地址
	private static String atUrl = "https://api.weixin.qq.com/cgi-bin/token";//access_token
	private static String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";//获取手机号
	private static String msgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";//模板消息
	private static String qrCodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";//小程序码
	
	
	@PostConstruct
    public void init() {
		sessionManager = this.sessionManagerSelf;
    }
	
	/**
	 * 获取登录信息
	 *
	 */
	public static Map<String, String> getLoginInfo(String code) {
		
		String appId = ConstantsContext.wxAppid();
		String appSecret = ConstantsContext.wxAppSecret();
		
		Map<String, String> map = new HashMap<String, String>();
		
		String params = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
		String sr = HttpRequest.sendGet(loginUrl, params);
		//解析相应内容（转换成json对象）
	    JSONObject json = JSONObject.parseObject(sr);
	    //用户的唯一标识（openid）
	    String openid = (String) json.get("openid");
	    
	    String unionid = "";
	    if(json.containsKey("unionid")) {
	    	unionid = (String) json.get("unionid");
	    }
	    
	    map.put("unionid", unionid);
	    map.put("openid", openid);
	    
		return map;
	}
	
	
	/**
	 * 获取手机号码
	 *
	 */
	public static String getPhoneNum(String code) {
		String access_token = "123";
		
		JSONObject json = new JSONObject();
		json.put("code", code);
		String jsonstr = JSONObject.toJSONString(json);
		String ret = HttpRequest.sendPost(phoneUrl+"?access_token=" + access_token, jsonstr);
		
		JSONObject res = JSONObject.parseObject(ret);
		
		Integer errcode = res.getInteger("errcode");
		if(errcode==0) {
			JSONObject phoneinfo = res.getJSONObject("phone_info");
			String phone = phoneinfo.getString("phoneNumber");
			return phone;
		}else {
			return null;
		}
	}


	public static String getAccessToken() {
		
		String appId = ConstantsContext.wxAppid();
		String appSecret = ConstantsContext.wxAppSecret();
		
		String at = "";
		
		if(sessionManager.hasSession(ACCESS_TOKEN_KEY)) {//未过期
			at = (String) sessionManager.querySession(ACCESS_TOKEN_KEY);
		}else {//已过期 重新获取
			String params = "appid=" +appId + "&secret=" + appSecret + "&grant_type=client_credential";
			String sr = HttpRequest.sendGet(atUrl, params);
			JSONObject json = JSONObject.parseObject(sr);
			at = json.getString("access_token");
			//放入redis缓存 过期时间110分钟
			sessionManager.setSession(ACCESS_TOKEN_KEY, at, 110);
		}
		return at;
	}
	
	
	/**
	 * 生成小程序码
	 * @param aqc 页面参数
	 * @param savePath
	 * @param saveName
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static InputStream getQRCode(AppQrCode aqc) throws ClientProtocolException, IOException {

		if(ToolUtil.isEmpty(aqc.getEnv_version())) {
			aqc.setEnv_version("release");
		}

		String access_token = getAccessToken();

		String jsonstr = JSONObject.toJSONString(aqc);

		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		HttpPost httpPost = new HttpPost(qrCodeUrl+"?access_token="+access_token);  // 接口
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
		StringEntity entity = null;
		try {
			entity = new StringEntity(jsonstr);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		entity.setContentType("image/png");
		httpPost.setEntity(entity);
		HttpResponse response;

		response = httpClient.execute(httpPost);
		InputStream inputStream = response.getEntity().getContent();
		return inputStream;  //保存图片
	}
	
	
	
	public static String inputStream2Base64(InputStream is) throws Exception {
        byte[] data = null;
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }

        return Base64.getEncoder().encodeToString(data);
    }
}
